package com.mb.app.controller;

import com.mb.app.domain.TbCoupons;
import com.mb.app.service.ITbCouponsService;
import com.mb.common.controller.BaseController;
import com.mb.common.utils.DateUtils;
import com.mb.common.utils.PageUtils;
import com.mb.common.utils.Query;
import com.mb.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 优惠劵服务  前端控制器
 * </p>
 *
 * @author wuhanlin
 * @since 2019-05-20
 */
@Controller
@RequestMapping("/app/coupon")
@Slf4j
public class TbCouponController extends BaseController {

    @Autowired
    private ITbCouponsService couponsService;

    @GetMapping("/index")
    String index(){
        return "/app/coupon/coupon_list";
    }

    @ResponseBody
    @GetMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        // 时间截取
        String createTime = (String) params.get("createTime");
        if (StringUtils.isNotEmpty(createTime)) {
            params.put("startTime", DateUtils.parse(createTime.substring(0,10),DateUtils.DATE_PATTERN));
            params.put("endTime",createTime.substring(13,23)+" 23:59:59");
        }
        Query query = new Query(params);
        List<TbCoupons> list = couponsService.queryList(query);
        int total = couponsService.count(query);
        PageUtils pageUtils = new PageUtils(list, total);
        return pageUtils;
    }


    @ResponseBody
    @PostMapping("/remove")
    public R remove(@RequestParam("couponId") Long couponId, HttpServletRequest request){
        Long delUserId = getUserId();
        int result = couponsService.remove(couponId,delUserId);
        return R.ok();
    }

    @GetMapping("/dtl/{couponId}")
    String dtl(@PathVariable("couponId") Long couponId, Model model){
        model.addAttribute("couponInfo",couponsService.getDtl(couponId));
        return "/app/coupon/coupon_info";
    }


    @GetMapping("/edit/{couponId}")
    String edit(@PathVariable("couponId") Long couponId, Model model){
        model.addAttribute("couponInfo",couponsService.getDtl(couponId));
        return "/app/coupon/coupon_edit";
    }


    @ResponseBody
    @PostMapping("/update")
    public R update(TbCoupons TbCoupons, HttpServletRequest request){
        int result = couponsService.update(TbCoupons);
        return R.ok();
    }

}
